<template>
  <el-card>
    <template #header>
      <PlusSearch
        v-model="state"
        :columns="searchColumns"
        :show-number="2"
        label-width="80"
        label-position="right"
        @change="handleChange"
        @search="handleSearch"
        @reset="handleRest"
      />
    </template>
    <el-alert title="TODO:数据状态显示" type="info" :closable="false" />
    <pure-table
      adaptive
      :adaptiveConfig="adaptiveConfig"
      :data="tableData"
      :columns="columns"
      :row-class-name="tableRowClassName"
    >
      <template #aqiLevel="{ row }">
        <span :style="{ color: row.aqi.aqiColor }"
          >{{ row.aqi.aqiLevelDes }}({{
            convertLevelToChinese(row.aqi.aqiLevel)
          }})</span
        >
      </template>
      <template #operation="{ row }">
        <el-button link type="primary" size="small" @click="handleClick(row)">
          Detail
        </el-button>
      </template>
    </pure-table>
    <el-pagination
      small
      background
      right
      layout="prev, pager, next"
      :page-count="totalPage"
      :page-size="pageSize"
      class="mt-4"
      @current-change="handlePageChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import {
  getAqiMeasuredDetail,
  getMeasuredResultTotalPage
} from "@/api/aqiMeasuredResult";
import { getGridProvinceById, listProvinces } from "@/api/gridProvince";
import { getGridCityById, getGridCityByProvinceId } from "@/api/gridCity";
import { getAqiGradeByLevel } from "@/api/aqiGrade";
import { ref, onMounted } from "vue";
import "plus-pro-components/es/components/search/style/css";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import { ca } from "element-plus/es/locales.mjs";
import { column } from "element-plus/es/components/table-v2/src/common.mjs";
import { options } from "node_modules/axios/index.cjs";
import { i } from "node_modules/vite/dist/node/types.d-aGj9QkWt";
import { integer } from "vue-types";
import { useResultInfoStoreHook } from "@/store/modules/resultInfo";

defineOptions({
  name: "Result"
});
const tableData = ref([]);
const totalPage = ref(1);
const pageSize = ref(2);
const pageNum = ref(1);
const router = useRouter();

const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  if (rowIndex === 1 || rowIndex === 5) {
    return "pure-warning-row";
  } else if (rowIndex === 3 || rowIndex === 7) {
    return "pure-success-row";
  }
  return "";
};

/** 获取省份列表 */
const getProvinceList = async () => {
  try {
    const { data } = await listProvinces();
    console.log("provinces");
    console.log(data);
    const provinces = data.map(province => ({
      value: province.provinceId,
      label: province.provinceName,
      children: []
    }));
    for (const province of provinces) {
      const cityData = await getCityByProvinceId(province.value);
      const cities = cityData.map(city => ({
        value: city.cityId,
        label: city.cityName
      }));

      province.children = cities; // 将城市信息添加到对应省份的children属性中
    }
    return provinces;
  } catch (e) {
    console.log(e);
  }
};

/**根据省份id获取城市信息 */
const getCityByProvinceId = async (provinceId: number) => {
  try {
    const { data } = await getGridCityByProvinceId(provinceId);
    console.log(data);
    return data;
  } catch (e) {
    console.log(e);
  }
};

const columns: TableColumnList = [
  {
    label: "编号",
    prop: "aqiMeasuredResult.aqimrId",
    width: "80"
  },
  {
    label: "网格员姓名",
    prop: "inspector.insName"
  },
  {
    label: "监督员姓名",
    prop: "monitor.monName"
  },
  {
    label: "所在省",
    prop: "gridProvince.provinceName"
  },
  {
    label: "所在市",
    prop: "gridCity.cityName"
  },
  {
    label: "AQI等级",
    prop: "aqiValue",
    slot: "aqiLevel"
  },
  {
    label: "地址",
    prop: "aqiMeasuredResult.aqimrAddress"
  },
  {
    label: "确认日期",
    prop: "aqimrDate",
    formatter: row => {
      return row.aqiMeasuredResult.aqimrMeasuredTime.split("T")[0];
    }
  },
  {
    label: "确认时间",
    prop: "aqimrTime",
    formatter: row => {
      return row.aqiMeasuredResult.aqimrMeasuredTime
        .split("T")[1]
        .split(".")[0];
    }
  },
  {
    label: "操作",
    width: "120",
    fixed: "right",
    slot: "operation"
  }
];
const searchColumns: PlusColumn[] = [
  {
    label: "反馈编号",
    prop: "fbId",
    valueType: "input"
  },
  {
    label: "电话",
    prop: "insTel",
    valueType: "copy",
    tooltip: "电话应为11位有效数字"
  },
  {
    label: "确认时间",
    prop: "aqimrMeasuredTime",
    valueType: "date-picker",
    fieldProps: {
      type: "datetimerange",
      startPlaceholder: "请选择",
      endPlaceholder: "请选择"
    }
  },
  {
    label: "省份",
    prop: "provinces",
    valueType: "cascader",
    options: getProvinceList()
  },
  {
    label: "地区",
    prop: "aqimrAddress",
    tooltip: "请精确到门牌号",
    fieldProps: {
      placeholder: "请精确到门牌号"
    }
  }
];

const aqiMeasuredResultParam = ref({});

const getTableData = async () => {
  try {
    console.log(aqiMeasuredResultParam.value, "aqiMeasuredResultParam");
    const { data } = await getAqiMeasuredDetail({
      aqiMeasuredResultParam: aqiMeasuredResultParam.value,
      pageSize: pageSize.value,
      pageNum: pageNum.value
    });
    console.log(data, "data");
    const updatedList = await Promise.all(
      data.list.map(async item => ({
        ...item,
        aqi: await getAqiByLevel(item.aqiValue)
      }))
    );
    tableData.value = updatedList;
    console.log(tableData.value, "tableData");
    console.log(data.list);
  } catch (e) {
    console.log(e);
  }
};

const getTableTotalPage = async () => {
  try {
    const total = await getMeasuredResultTotalPage({
      aqiMeasuredResultParam: aqiMeasuredResultParam.value,
      pageSize: pageSize.value
    });
    totalPage.value = total.data;
    console.log(totalPage.value, "totalPage");
  } catch (e) {
    console.log(e);
  }
};

/**根据aqi等级获取aqi信息 */
const getAqiByLevel = async (aqiValue: number) => {
  try {
    const { data } = await getAqiGradeByLevel(aqiValue);
    console.log(data);
    return data;
  } catch (e) {
    console.log(e);
  }
};

onMounted(() => {
  getTableData();
  getTableTotalPage();
  getProvinceList();
  console.log(tableData);
});

//search from
const state = ref({
  status: "0",
  time: new Date().toString()
});

const handleChange = (values: any) => {
  console.log(values, "change");
};
const handleSearch = (values: any) => {
  let provinceId = values.provinces?.[0] ?? null;
  let cityId = values.provinces?.[1] ?? null;
  let aqimrStartDate = values.aqimrMeasuredTime?.[0] ?? null;
  let aqimrEndDate = values.aqimrMeasuredTime?.[1] ?? null;
  aqiMeasuredResultParam.value = {
    ...values,
    provinceId,
    cityId,
    aqimrStartDate,
    aqimrEndDate
  };
  getTableData();
  getTableTotalPage();
  console.log(values, "search");
};
const handleRest = () => {
  aqiMeasuredResultParam.value = {};
  getTableData();
  getTableTotalPage();
  console.log("handleRest");
};

//分页
const handlePageChange = (currentPage: number) => {
  pageNum.value = currentPage;
  getTableData();
};

// 定义一个辅助函数，将数字转换为中文
const convertLevelToChinese = (level: number): string => {
  switch (level) {
    case 1:
      return "一";
    case 2:
      return "二";
    case 3:
      return "三";
    case 4:
      return "四";
    case 5:
      return "五";
    case 6:
      return "六";
    default:
      return "";
  }
};

//表格大小自适应
const adaptiveConfig: AdaptiveConfig = {
  /** 表格距离页面底部的偏移量，默认值为 `96` */
  offsetBottom: 85,
  /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
  fixHeader: true
};

//选中
const handleClick = (row: any) => {
  console.log(row, "click");
  useResultInfoStoreHook().SET_AQIMEASUREDRESULT(row.aqiMeasuredResult);
  useResultInfoStoreHook().SET_MONITOR(row.monitor);
  useResultInfoStoreHook().SET_INSPECTOR(row.inspector);
  useResultInfoStoreHook().SET_CITYNAME(row.gridCity.cityName);
  useResultInfoStoreHook().SET_PROVINCENAME(row.gridProvince.provinceName);
  useResultInfoStoreHook().SET_AQI(row.aqi);
  router.push("/resultInfo");
};
</script>

<style>
/* 此处样式会在全局都生效，上面 tableRowClassName 函数返回的值也就是类名必须在全局中唯一，避免样式突出 */
.pure-warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.pure-success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
